package com.gouda.employee.api.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gouda.employee.api.constant.Constant;
import com.gouda.employee.api.exception.ErrorCode;
import com.gouda.employee.api.exception.RequestException;
import com.hephaestus.exception.CheckFailureException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: souu
 * Date: 15-3-26
 * Time: 下午4:17
 * To change this template use File | Settings | File Templates.
 */
@Slf4j
public class JsonFilter implements Filter {

    private static final ObjectMapper jsonMapper = new ObjectMapper();

    private static final int OUT_BODY_MAXLENGTH = 1000;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
//        try {
//            Configuration config = new PropertiesConfiguration("config.properties");
//            this.isCheckHeader = config.getBoolean("web.checkheader", true);
//        } catch (ConfigurationException e) {
//            throw new RuntimeException(e);
//        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        long start = System.currentTimeMillis();

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        StringBuilder logInfo = new StringBuilder();
        String queryString = req.getQueryString();
        String uri = req.getRequestURI();
        if (StringUtils.isNotBlank(queryString)) {
            uri += "?" + queryString;
        }
        String body = getRequestBody(req);

        Map<String, String> header = _getRequestHeader(req, resp, uri);

        req.setAttribute(Constant.WEBKEY_HEADER, header);
        req.setAttribute(Constant.WEBKEY_BODY, body);
        logInfo.append(getInputLog(uri, header, body));
        log.info(logInfo.toString() + " " + (System.currentTimeMillis() - start) + "ms");
        chain.doFilter(req, resp);
    }

    private Map<String, Object> handleException(Exception e) {
        Map<String, Object> result = new LinkedHashMap<String, Object>();

        if (e instanceof RequestException) {
            RequestException reqEx = (RequestException) e;
            ErrorCode ec = reqEx.getEc();
            result.put("code", ec.getCode());
            result.put("msg", ec.getMessage());
            result.put("result", reqEx.getMessage());
        } else if (e.getCause() instanceof RequestException) {
            RequestException reqEx = (RequestException) e.getCause();
            ErrorCode ec = reqEx.getEc();
            result.put("code", ec.getCode());
            result.put("msg", ec.getMessage());
            result.put("result", reqEx.getMessage());
        } else if (e.getCause() instanceof CheckFailureException) {
            CheckFailureException cfe = (CheckFailureException) e.getCause();
            result.put("code", ErrorCode.EC_400004.getCode());
            result.put("msg", cfe.getMessage());
        } else {
            result.put("code", "500000");
            result.put("msg", "服务器内部异常");
            log.error(e.getMessage(), e);
        }

        return result;
    }

    public String getRequestBody(HttpServletRequest req) throws RequestException {
        StringBuilder body = new StringBuilder();

        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(req.getInputStream()));

            String line = null;
            while ((line = br.readLine()) != null) {
                body.append(line);
            }
        } catch (IOException e) {
            throw new RequestException(ErrorCode.EC_400000);
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                log.warn("close request stream fail");
            }
        }

        return body.toString();
    }


    private Map<String, String> _getRequestHeader(HttpServletRequest req, HttpServletResponse resp, String uri)
            throws RequestException {
        Map<String, String> header = new HashMap<String, String>();

        // set headers
        Enumeration<String> names = req.getHeaderNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            String value = req.getHeader(name);
            header.put(name, value);
        }

        return header;
    }

    /**
     * show header and body as log.
     */
    private String getInputLog(String uri, Map<String, String> header, String inputBody) {
        StringBuilder info = new StringBuilder("input - ");
        info.append("uri-").append(uri);
        info.append(" header-{");
        for (Map.Entry<String, String> entry : header.entrySet()) {
            info.append(entry.getKey()).append("=").append(entry.getValue()).append(",");
        }
        info.deleteCharAt(info.length() - 1);
        info.append("}");
        info.append(" body-").append(inputBody);
        return info.toString();
    }

    @Override
    public void destroy() {
    }

}
